package main

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"strings"
)

func main() {
	firstArg := os.Args[1]
	// 在 Windows 上使用 `tasklist` 命令获取所有进程信息
	cmd := exec.Command("tasklist")
	var out bytes.Buffer
	cmd.Stdout = &out

	err := cmd.Run()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// 打印输出
	fmt.Println(out.String())

	// 解析输出（示例）
	lines := strings.Split(out.String(), "\n")
	for _, line := range lines[2:] { // 跳过前两行标题和空行
		if line == "" {
			continue
		}
		fields := strings.Fields(line)
		name := fields[0]
		pid := fields[1]
		sessionName := fields[2]
		sessionNum := fields[3]
		memUsage := fields[4]
		cpuTime := strings.Join(fields[5:], " ")
		if name == firstArg {
			fmt.Printf("Name: %s, PID: %s, Session Name: %s, Session#: %s, Mem Usage: %s, CPU Time: %s\n", name, pid, sessionName, sessionNum, memUsage, cpuTime)
			cmd := exec.Command("taskkill", "/F", "/PID", pid)

			// 运行命令并获取输出
			output, err := cmd.CombinedOutput()
			if err != nil {
				fmt.Printf("Error executing taskkill: %v\n", err)
				fmt.Printf("Output: %s\n", string(output))
				return
			}

			fmt.Printf("Successfully killed process with PID %s\n", pid)
		}
	}
}
